package middleware

import (
	"net/http"
	"strings"

	"game-simple/internal/framework/auth/services"
	"github.com/gin-gonic/gin"
)

// Middleware 认证中间件
func Middleware() gin.HandlerFunc {
	service := services.NewService()

	return func(ctx *gin.Context) {
		token := getTokenFromHeader(ctx)
		if token == "" {
			ctx.JSON(http.StatusUnauthorized, gin.H{"error": "缺少 token"})
			ctx.Abort()
			return
		}

		user, err := service.ValidateToken(token)
		if err != nil {
			ctx.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
			ctx.Abort()
			return
		}

		ctx.Set("user", user)
		ctx.Set("user_id", user.ID)
		ctx.Next()
	}
}

// OptionalMiddleware 可选的认证中间件（不强制要求 token）
func OptionalMiddleware() gin.HandlerFunc {
	service := services.NewService()

	return func(ctx *gin.Context) {
		token := getTokenFromHeader(ctx)
		if token != "" {
			user, err := service.ValidateToken(token)
			if err == nil && user != nil {
				ctx.Set("user", user)
				ctx.Set("user_id", user.ID)
			}
		}
		ctx.Next()
	}
}

func getTokenFromHeader(ctx *gin.Context) string {
	authHeader := ctx.GetHeader("Authorization")
	if authHeader == "" {
		return ""
	}

	parts := strings.Split(authHeader, " ")
	if len(parts) != 2 || parts[0] != "Bearer" {
		return ""
	}

	return parts[1]
}

